<template>
  <scroll-view scroll-y="ture" style="height: 100vh">
    <view
      class="ultraman-container"
      :style="{
        backgroundImage: `url(${oss2('others/ultraman/input_bg.png')})`,
      }"
    >
      <view
        class="back_btn"
        @click="backIndex"
        :style="{
          backgroundImage: `url(${oss2('others/ultraman/input_back_btn.png')})`,
        }"
      ></view>
      <view
        class="rule_btn"
        @click.stop="openRule"
        :style="{
          backgroundImage: `url(${oss2('others/ultraman/input_rule_btn.png')})`,
        }"
      ></view>

      <view
        class="input_content"
        :style="{
          backgroundImage: `url(${oss2(
            'others/ultraman/input_content_bg.png'
          )})`,
        }"
      >
        <view
          class="input_pic"
          :style="{
            backgroundImage: `url(${oss2('others/ultraman/input_pic.png')})`,
          }"
        ></view>
        <view
          class="input_box_bg"
          :style="{
            backgroundImage: `url(${oss2('others/ultraman/input_box_bg.png')})`,
          }"
        >
          <view class="input_box">
            <input
              @focus="focusInput"
              @change="inputChange"
              v-model="code"
              placeholder="请输入字符串"
              placeholder-style="color: rgba(1, 0, 1,0.2);"
            />
            <view
              class="search_icon"
              :style="{
                backgroundImage: `url(${oss2(
                  'others/ultraman/input_search_icon.png'
                )})`,
              }"
            >
            </view>
          </view>
        </view>
      </view>

      <view class="bottom_btn items-center">
        <view
          @click="canceBtn"
          :style="{
            backgroundImage: `url(${oss2(
              'others/ultraman/input_cancel_btn.png'
            )})`,
          }"
        ></view>

        <view
          @click="scanCode"
          :style="{
            backgroundImage: `url(${oss2(
              'others/ultraman/input_confirm_btn.png'
            )})`,
          }"
        ></view>
      </view>

      <view
        class="ultraman_sign"
        :style="{
          backgroundImage: `url(${oss2('others/ultraman/ultraman_gs.png')})`,
        }"
      >
      </view>
    </view>

    <!-- 弹窗 -->
    <view class="mode" v-if="showDialog">
      <view
        class="Dialog_body w-375px top-21vh left-0px"
        :class="highDialog ? 'high' : ''"
        :style="{
          backgroundImage: `url(${oss2('others/ultraman/' + dialogBg)})`,
        }"
      >
        <view class="Dialog_close" @click.stop="dialogClose"></view>
        <view
          class="Dialog_back w-168px h-58px bottom-77px left-104px"
          @click.stop="dialogBack"
          :style="{
            backgroundImage: `url(${oss2('others/ultraman/code_back.png')})`,
          }"
        ></view>
        <view
          class="Dialog_rule w-65px h-11px bottom-56px left-156px"
          @click.stop="openRule2"
          :style="{
            backgroundImage: `url(${oss2('others/ultraman/rule_check.png')})`,
          }"
        >
        </view>
      </view>
    </view>

    <!-- 活动规则弹窗 -->
    <rule-popup v-if="showRule" @close="showRule = false" />
  </scroll-view>


</template>

  <script setup>
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import { ref } from "vue";
import { oss2, generateSign2, message } from "@/utils/utils";
import RulePopup from "./components/rule-popup.vue";
import { userLogin } from "@/services/utils";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";
let scanStauts = {
  4001: { img: "code_wait.png", btn: "ultraman_campaign_scan_nonactivated" },
  4002: { img: "code_past.png", btn: "ultraman_campaign_scan_invalid" },
  4000: {
    img: "code_input_err.png",
    btn: "ultraman_campaign_manual_redeem_fail",
  },
};

const code = ref("");
const showRule = ref(false);
const showDialog = ref(false);
const dialogCode = ref(0);
const dialogBg = ref("");
const highDialog = ref(false);

onLoad(async (query) => {});
onShow(() => {
  // 用户进入时间
  enterTime = new Date();
  getApp().accessLogAdd();
});
onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  getApp().emdlz2(
    "track",
    "event",
    "ultraman_campaign_manual_redeem",
    "view",
    "campaign_manual_redeem_page",
    stayTime
  );
});
onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  getApp().emdlz(
    "track",
    "event",
    "ultraman_campaign_manual_redeem",
    "view",
    "campaign_manual_redeem_page",
    stayTime
  );
});

const linkTo = (url) => uni.navigateTo({ url });

const scanCode = () => {
  getApp().emdlz(
    "track",
    "event",
    "ultraman_campaign_manual_redeem",
    "click",
    "confirm",
    ""
  );

  if (code.value === "") return message("请输入字符串!");
  const body = {
    userValue: uni.getStorageSync("OPENID"),
    qrCode: code.value,
    source: "mini",
    timestamp: Date.parse(new Date()),
  };
  uni.request({
    url: `${process.env.ALTRAMAN_URL}/zex-qr/api/qr/validation`,
    method: "get",
    data: {
      ...body,
      ...{ sign: generateSign2(body) },
    },

    success: async (res) => {
      if (res.data.code === 200) {
        // 是否登录注册
        if (!uni.getStorageSync("TOKEN")) {
          // 静默拿取微信用户的 openId 与 unionId 信息
          uni.login({
            provider: "weixin",
            success: async (res) => {
              const loginParam = {
                type: 1,
              };
              loginParam.code = res.code;
              const { data } = await userLogin(loginParam);
              uni.setStorageSync("TOKEN", data?.accessToken);
              uni.setStorageSync("OPENID", data?.openId);
              uni.setStorageSync("UNIONID", data?.unionId);
              getApp().emdlz("set", "user", "openid", data?.openId);
              getApp().emdlz("set", "user", "unionId", data?.unionId);
              linkTo(
                `/campaign/pages/ultraman/webview?accesstoken=${uni.getStorageSync(
                  "TOKEN"
                )}&code=${code.value}&openid=${uni.getStorageSync(
                  "OPENID"
                )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
                  getApp().globalData.user.memberScore.memberId
                }&agree=${uni.getStorageSync("PANDAAGREE")}`
              );
              code.value = "";
            },
          });
        } else {
          linkTo(
            `/campaign/pages/ultraman/webview?accesstoken=${uni.getStorageSync(
              "TOKEN"
            )}&code=${code.value}&openid=${uni.getStorageSync(
              "OPENID"
            )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
              getApp().globalData.user.memberScore.memberId
            }&agree=${uni.getStorageSync("PANDAAGREE")}`
          );
          code.value = "";
        }
      } else if ([4000].includes(res.data.code)) {
        code.value = "";
        dialogCode.value = 4000;
        dialogBg.value = scanStauts[4000].img;
        highDialog.value = true;
        showDialog.value = true;
      } else if ([4001].includes(res.data.code)) {
        code.value = "";
        dialogCode.value = 4001;
        dialogBg.value = scanStauts[4001].img;
        highDialog.value = false;
        showDialog.value = true;
      } else if ([4002].includes(res.data.code)) {
        code.value = "";
        dialogCode.value = 4002;
        dialogBg.value = scanStauts[4002].img;
        highDialog.value = false;
        showDialog.value = true;
      } else {
        code.value = "";
        uni.showToast({
          title: res.data.message,
          icon: "none",
          duration: 2000,
        });
      }
    },
    fail: async (err) => {
      code.value = "";
      uni.showToast({
        title: err.data.message,
        icon: "none",
        duration: 2000,
      });
    },
  });
};

const backIndex = () => {
  getApp().emdlz(
    "track",
    "event",
    "ultraman_campaign_manual_redeem",
    "click",
    "return_landing_page",
    ""
  );
  uni.navigateBack({
    delta: 1,
  });
};
const openRule = () => {
  getApp().emdlz(
    "track",
    "event",
    "ultraman_campaign_manual_redeem",
    "click",
    "check_activity_rule",
    ""
  );
  showRule.value = true;
};
const openRule2 = () => {
  getApp().emdlz(
    "track",
    "event",
    scanStauts[dialogCode.value].btn,
    "click",
    "check_activity_rule",
    ""
  );
  showRule.value = true;
};
const focusInput = () => {
  getApp().emdlz(
    "track",
    "event",
    "ultraman_campaign_manual_redeem",
    "click",
    "input_code",
    ""
  );
};
const inputChange = () => {
  console.log("wwwwwww", code.value);
};
const canceBtn = () => {
  getApp().emdlz(
    "track",
    "event",
    "ultraman_campaign_manual_redeem",
    "click",
    "cancel",
    ""
  );

  uni.navigateBack({
    delta: 1,
  });
};
const dialogClose = () => {
  getApp().emdlz(
    "track",
    "event",
    scanStauts[dialogCode.value].btn,
    "click",
    "pop_up_close",
    ""
  );
  showDialog.value = false;
};
const dialogBack = () => {
  getApp().emdlz(
    "track",
    "event",
    scanStauts[dialogCode.value].btn,
    "click",
    "pop_up_return",
    ""
  );
  showDialog.value = false;
};

onShareAppMessage((e) => {
  const shareObj = {
    title: "打开迷你奥利奥，扫码互动赢奥特曼大奖，还可集图鉴兑更多好礼！", // 默认是小程序的名称(可以写slogan等)
    path: "/campaign/pages/ultraman/index?from=pubid:shareback;aid:sharecard", // 默认是当前页面，必须是以‘/’开头的完整路径
    imageUrl: oss2("others/ultraman/share_ultraman.jpg"), //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    success: (res) => {
      // 转发成功之后的回调
      if (res.errMsg == "shareAppMessage:ok") {
      }
    },
    fail: (err) => {
      // 转发失败之后的回调
      console.log("转发失败之后的回调", err);
      if (res.errMsg == "shareAppMessage:fail cancel") {
        // 用户取消转发
        console.log("用户取消转发");
      } else if (res.errMsg == "shareAppMessage:fail") {
        // 转发失败，其中 detail message 为详细失败信息
        console.log("转发失败，其中detail message 为详细失败信息");
      }
    },
    complete: () => {
      // 转发结束之后的回调（转发成不成功都会执行）
      console.log("转发结束之后的回调（转发成不成功都会执行）");
    },
  };
  console.log(shareObj);
  return shareObj;
});
</script>

  <style>
page {
  background-color: #02071e !important;
}
</style>
  <style lang="less" scoped>
.ultraman-container {
  position: relative;
  width: 100%;
  min-height: 724px;
  height: 100vh;
  background-color: #08204e;
  background-repeat: no-repeat;
  background-position: top left;
  background-size: 375px 784px;

  .back_btn {
    position: absolute;
    top: 14px;
    left: 17px;
    width: 90px;
    height: 36px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 90px 100%;
  }
  .rule_btn {
    position: absolute;
    top: 14px;
    right: 20px;
    width: 90px;
    height: 36px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 90px 100%;
  }
  .input_content {
    position: absolute;
    top: 46px;
    left: 0;
    width: 375px;
    height: 600px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 375px 100%;
    box-sizing: border-box;
    padding: 51px 66px 0;
    .input_pic {
      width: 244px;
      height: 463px;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 244px 100%;
    }
    .input_box_bg {
      position: absolute;
      top: 463px;
      left: 48px;
      width: 280px;
      height: 75px;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 280px 100%;
      .input_box {
        position: absolute;
        top: 22px;
        left: 20px;
        width: 240px;
        height: 32px;
        input {
          width: 240px;
          height: 32px;
          background: #ffffff;
          border-radius: 16px;
          box-sizing: border-box;
          padding: 0 17px;
          font-size: 16px;
          font-family: Source Han Sans CN;
          font-weight: 400;
        }
        .search_icon {
          width: 20px;
          height: 20px;
          background-repeat: no-repeat;
          background-position: top left;
          background-size: 20px 100%;
          position: absolute;
          top: 7px;
          right: 14px;
        }
      }
    }
  }
  .bottom_btn {
    position: absolute;
    left: 0;
    top: 634px;
    width: 100%;
    height: 58px;
    box-sizing: border-box;
    padding: 0 24px;
    display: flex;
    justify-content: space-between;
    view {
      width: 153px;
      height: 58px;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 153px 100%;
    }
  }

  .ultraman_sign {
    width: 75px;
    height: 8px;
    position: absolute;
    top: 716px;
    left: 150px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 100% 100%;
  }
}

.mode {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 90;
  background-color: rgba(10, 28, 108, 0.7);

  .Dialog_body {
    position: absolute;
    height: 384px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 100% 100%;
    .Dialog_close {
      position: absolute;
      top: 42px;
      right: 60px;
      width: 33px;
      height: 33px;
      background-color: transparent;
    }
    .Dialog_back,
    .Dialog_rule {
      position: absolute;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 100% 100%;
    }
  }
  .high {
    height: 403px;
    .Dialog_close {
      top: 23px;
      right: 47px;
    }
  }
}
</style>
